//@ANDROIDONLYFILE@//
//@ANDROIDONLYFILE@//
package com.bluetane.android;

import java.io.IOException;
import java.util.UUID;

import com.bluetane.android.BluetaneEvent.BluetaneEventType;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;

import android.bluetooth.BluetoothSocket;

public class ConnectThread extends Thread
{
	private final BluetoothSocket socket;
	private BluetoothAdapter localBluetooth;
	private BluetaneEventSource eventSource;
	
	public ConnectThread(BluetoothAdapter startlocalBluetooth, BluetoothDevice remoteDevice, UUID uniqueID, BluetaneEventSource startEventSource)
	{
		localBluetooth = startlocalBluetooth;
		eventSource = startEventSource;
		BluetoothSocket tempSocket = null;
		try
		{
			tempSocket = remoteDevice.createRfcommSocketToServiceRecord(uniqueID);
		}
		catch (IOException e)
		{
			// Socket Error
		}
		socket = tempSocket;
	}
	
	public void run()
	{
		localBluetooth.cancelDiscovery();
		try
		{
			socket.connect();
			
			BtConnection socketConnection = new BtConnection(socket, eventSource);
			eventSource.fireEvent(new BluetaneEvent(this, BluetaneEventType.ConnectionEstablished, socketConnection));
			
		}
		catch (IOException connectException)
		{
			try
			{
				socket.close();
			}
			catch (IOException closeException)
			{
			}
		}
	}
	
	public void cancel()
	{
		try
		{
			socket.close();
		}
		catch (IOException e)
		{
		}
	}
}
